<template>
  <div class="DBPage-comp-ct">
  
  <mt-header title="数据库Demo" fixed>
    <mt-button icon="back" @click="$router.back(-1)" slot="left">返回</mt-button>
  </mt-header>
    <mt-button size='large' type="primary" @click="openDB" class="cut_button">openDB</mt-button>
    <mt-button size='large' type="primary" @click="getList" class="cut_button">getList</mt-button>
    <mt-button size='large' type="primary" @click="addUser" class="cut_button">add_user</mt-button>
    <hr>
    <ul>
      <li v-for="(item,idx) of list" :key="idx" class="item">
         {{item.name}}:{{item.psw}}
      </li>
    </ul>
  </div>
</template>
<script>
import DBUtil from '@/cordova_plugins/DBUtil.js'
export default {
  name: 'DBPage',
  data() {
    return {
    list:[
      {name:'test',psw:'123'},
      {name:'test',psw:'123'},
      {name:'test',psw:'123'}
    ],
    db:false
    }
  },
  methods: {
    openDB() {
      console.log('open db');
      //打开数据库
      DBUtil.DB_open({name:'my.db'})

      //如果不存在user表就初始化
      let sqls = []
      sqls.push('DROP TABLE IF EXISTS user')
      sqls.push('create table user(name,psw)')
      sqls.push("insert into user(name,psw) values('longjian','888888')")
      sqls.push("insert into user(name,psw) values('longjian2','888888')")
      sqls.push("insert into user(name,psw) values('longjian3','888888')")

      DBUtil.sqlBatch(sqls,()=>{
        alert('DBinit ok')
      },(erro)=>{
        alert(JSON.stringify(erro))
      })
    },
    getList(){
      console.log('get List');
      //获取user表测试
      let sql = "select * from user"
      DBUtil.findRecord(sql,(ret)=>{
        // alert(JSON.stringify(ret))
        this.list = []
        // 列表数据获取规则
        for(let i = 0;i<ret.rows.length;i++){
          this.list.push(ret.rows.item(i))
        }
      },(err)=>{
        alert(JSON.stringify(err))
      })
    },
    addUser(){
      let new_user = {
        name:'new_zs',
        psw:'777777'
      }
      DBUtil.addRecord('user',new_user,(ret)=>{
        alert(JSON.stringify(ret))
      },(erro)=>{
        alert(JSON.stringify(erro))
      })
    }
  },
}
</script>
<style lang="scss" scoped>
.DBPage-comp-ct {
  .item{
    padding: 5px;
    border-bottom: 1px;
  }
  .cut_button{
     margin: 2px;
  }
}
</style>
